<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="header">
			<view class="header-left">
				<text class="header-title">规则管理</text>
				<text class="header-desc">管理您发布的规则解读</text>
			</view>
			<view class="header-right">
				<button class="add-btn" @click="navigateTo('/packageadmin/admin/rule-upload')">新增规则</button>
			</view>
		</view>
		
		<!-- 规则列表 -->
		<view class="rule-list" v-if="!loading">
			<view class="empty-data" v-if="ruleList.length === 0">
				<image class="empty-image" src="/static/images/empty-data.png" mode="aspectFit"></image>
				<text class="empty-text">暂无规则数据</text>
			</view>
			
			<view class="rule-item" v-for="(item, index) in ruleList" :key="index" @click="viewRuleDetail(item)">
				<view class="rule-content">
					<view class="rule-header">
						<view class="rule-title-row">
							<text class="rule-title">{{ item.title }}</text>
						</view>
						<view class="rule-info">
							<text class="rule-date">发布: {{ formatDate(item.createTime) }}</text>
							<text class="rule-category">{{ item.category }}</text>
						</view>
					</view>
					<view class="rule-summary">{{ item.description }}</view>
					<view class="rule-stats">
						<text class="stats-item">阅读: {{ item.viewCount || 0 }}</text>
					</view>
				</view>
				<view class="rule-actions">
					<view class="action-btn edit-btn" @click.stop="editRule(item)">
						<text class="action-icon">✏️</text>
						<text class="action-text">编辑</text>
					</view>
					<view class="action-btn delete-btn" @click.stop="confirmDeleteRule(item)">
						<text class="action-icon">🗑️</text>
						<text class="action-text">删除</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-container" v-if="loading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore && !loading && ruleList.length > 0" @click="loadMore">
			<text>加载更多</text>
		</view>
		
		<view class="load-all" v-if="!hasMore && ruleList.length > 0">
			<text>已加载全部数据</text>
		</view>
	</view>
</template>

<script>
	import { getToken } from '../../utils/tokenManager.js';
	
	export default {
	data() {
		// 获取当前日期
		const now = new Date();
		const year = now.getFullYear();
		const month = String(now.getMonth() + 1).padStart(2, '0');
		const day = String(now.getDate()).padStart(2, '0');
		const today = `${year}-${month}-${day}`;
		
		return {
			userInfo: null,
			userId: '',
			loading: true,
			refreshing: false,
			ruleList: [],
			page: 1,
			limit: 10,
			total: 0,
			hasMore: true,
			
			// 当前日期
			today: today,
			
			// 筛选参数
			filterParams: {
				title: '',
				category: '',
				status: '',
				startDate: '',
				endDate: ''
			},
			
			// 下拉选项
			categoryOptions: ['全部', '足球规则', '篮球规则', '排球规则', '其他规则'],
			categoryIndex: 0
		}
	},
	onLoad() {
		// 直接加载规则列表，不依赖用户信息
		this.directFetchRules();
		// 获取用户ID，用于删除等操作
		this.getUserId();
	},
	onPullDownRefresh() {
		this.refreshData();
	},
	methods: {
		// 直接从云端获取规则列表，不依赖用户信息
		directFetchRules() {
			this.loading = true;
			this.ruleList = [];
			
			console.log('正在直接获取规则列表...');
			
			// 从本地存储获取用户ID
			const userInfoStr = uni.getStorageSync('userInfo');
			let userId = '';
			if (userInfoStr) {
				try {
					const userInfo = JSON.parse(userInfoStr);
					userId = userInfo._id || userInfo.userId || userInfo.id || '';
					this.userId = userId;
				} catch (e) {
					console.error('解析用户信息失败', e);
				}
			}
			
			if (!userId) {
				userId = this.userId;
			}
			
			console.log('当前用户ID:', userId);
			
			(async () => {
				try {
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.getMyadminRules({
						page: 1,
						limit: 20,
						creatorId: userId
					});
					
					this.loading = false;
					console.log('云对象返回结果:', res);
					
					if (res && res.code === 0) {
						this.ruleList = res.data || [];
						this.total = res.total || 0;
						this.hasMore = this.ruleList.length < this.total;
						
						if (this.ruleList.length > 0) {
							this.page = 2;
						}
					} else {
						uni.showToast({
							title: res?.message || '获取数据失败',
							icon: 'none'
						});
					}
				} catch (err) {
					this.loading = false;
					console.error('调用云对象失败:', err);
					
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			})();
		},
		
		// 下拉刷新数据
		refreshData() {
			this.refreshing = true;
			this.directFetchRules();
		},
		
		// 加载更多
		loadMore() {
			if (this.hasMore && !this.loading) {
				this.loading = true;
				
				(async () => {
					try {
						const learningService = uniCloud.importObject('learning-service');
						const res = await learningService.getMyadminRules({
							page: this.page,
							limit: 10,
							creatorId: this.userId
						});
						
						this.loading = false;
						
						if (res && res.code === 0) {
							const newData = res.data || [];
							this.ruleList = [...this.ruleList, ...newData];
							this.total = res.total || 0;
							this.hasMore = this.ruleList.length < this.total;
							
							if (newData.length > 0) {
								this.page++;
							}
						} else {
							uni.showToast({
								title: res?.message || '获取数据失败',
								icon: 'none'
							});
						}
					} catch (err) {
						this.loading = false;
						console.error('调用云对象失败:', err);
						
						uni.showToast({
							title: '网络错误，请重试',
							icon: 'none'
						});
					}
				})();
			}
		},
		
		// 查看规则详情
		viewRuleDetail(rule) {
			uni.navigateTo({
				url: `/packageStudy/study/rule-detail?id=${rule._id}&from=management`
			});
		},
		
		// 编辑规则
		editRule(rule) {
			if (!rule || !rule._id) {
				uni.showToast({
					title: '无效的规则ID',
					icon: 'none'
				});
				return;
			}
			
			console.log('准备编辑规则, ID:', rule._id);
			
			// 将ID保存到本地存储，以防页面跳转过程中参数丢失
			uni.setStorageSync('edit_rule_id', rule._id);
			
			// 使用更可靠的传参方式
			const url = `/packageadmin/admin/rule-upload?id=${encodeURIComponent(rule._id)}&mode=edit&t=${Date.now()}`;
			console.log('跳转URL:', url);
			
			uni.navigateTo({
				url: url,
				fail: (err) => {
					console.error('页面跳转失败:', err);
					uni.showToast({
						title: '页面跳转失败',
						icon: 'none'
					});
				}
			});
		},
		
		// 确认删除规则
		confirmDeleteRule(rule) {
			uni.showModal({
				title: '确认删除',
				content: `确定要删除规则"${rule.title}"吗？此操作不可恢复。`,
				confirmText: '删除',
				confirmColor: '#ff4d4f',
				success: (res) => {
					if (res.confirm) {
						this.deleteRule(rule);
					}
				}
			});
		},
		
		// 获取用户ID，用于删除等操作
		getUserId() {
			// 从本地存储获取用户信息
			const userInfoStr = uni.getStorageSync('userInfo');
			if (userInfoStr) {
				try {
					const userInfo = JSON.parse(userInfoStr);
					this.userId = userInfo._id || userInfo.userId || userInfo.id || '';
					console.log('已获取用户ID:', this.userId);
				} catch (e) {
					console.error('解析用户信息失败', e);
					this.getCloudUserId();
				}
			} else {
				// 本地没有，从云端获取
				this.getCloudUserId();
			}
		},
		
		// 从云端获取用户ID
		async getCloudUserId() {
								try {
						const userService = uniCloud.importObject('user-service');
						const res = await userService.getUserInfo(getToken());
				
				if (res && res.code === 0 && res.data) {
					this.userId = res.data.userId || res.data._id || '';
					console.log('已从云端获取用户ID:', this.userId);
				} else {
					console.error('获取用户ID失败:', res);
				}
			} catch (err) {
				console.error('调用获取用户信息云对象失败', err);
			}
		},
		
		// 删除规则
		deleteRule(rule) {
			uni.showLoading({
				title: '删除中...'
			});
			
			// 如果没有用户ID，先获取
			if (!this.userId) {
				this.getUserId();
				uni.showToast({
					title: '请稍后再试',
					icon: 'none'
				});
				uni.hideLoading();
				return;
			}
			
			console.log('删除规则:', rule._id, '创建者ID:', this.userId);
			
			(async () => {
				try {
					const learningService = uniCloud.importObject('learning-service');
					const res = await learningService.deleteRule({
						ruleId: rule._id,
						creatorId: this.userId
					});
					
					uni.hideLoading();
					console.log('删除规则返回:', res);
					
					if (res.code === 0) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						
						// 从列表中移除该规则
						const index = this.ruleList.findIndex(item => item._id === rule._id);
						if (index > -1) {
							this.ruleList.splice(index, 1);
						}
					} else {
						uni.showModal({
							title: '删除失败',
							content: res.message || '未知错误',
							showCancel: false
						});
					}
				} catch (err) {
					uni.hideLoading();
					console.error('删除规则失败:', err);
					
					uni.showModal({
						title: '删除失败',
						content: '网络错误，请重试',
						showCancel: false
					});
				}
			})();
		},
		
		// 执行搜索
		handleSearch() {
			this.directFetchRules();
		},
		
		// 绑定分类选择
		bindCategoryChange(e) {
			this.categoryIndex = e.detail.value;
			this.filterParams.category = this.categoryOptions[this.categoryIndex];
			this.directFetchRules();
		},
		
		// 导航到指定页面
		navigateTo(url) {
			uni.navigateTo({
				url: url
			});
		},
		
		// 格式化日期
		formatDate(dateStr) {
			if (!dateStr) return '';
			
			const date = new Date(dateStr);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			
			return `${year}-${month}-${day}`;
		}
	}
}
</script>

<style>
	@import "../admin/app.css";
	
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		margin-bottom: 20rpx;
	}
	
	.header-left {
		display: flex;
		flex-direction: column;
	}
	
	.header-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}
	
	.header-desc {
		font-size: 24rpx;
		color: #999;
		margin-top: 6rpx;
	}
	
	.add-btn {
		background-color: #1BAE76;
		color: #fff;
		border: none;
		padding: 16rpx 30rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
		line-height: 1.5;
	}
	
	.rule-list {
		margin-bottom: 30rpx;
	}
	
	.rule-item {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		display: flex;
		flex-direction: column;
	}
	
	.rule-content {
		flex: 1;
	}
	
	.rule-header {
		margin-bottom: 16rpx;
	}
	
	.rule-title-row {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}
	
	.rule-title {
		flex: 1;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-right: 10rpx;
	}
	
	.rule-info {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}
	
	.rule-date, .rule-category {
		font-size: 24rpx;
		color: #999;
		margin-right: 20rpx;
	}
	
	.rule-summary {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 16rpx;
		line-height: 1.5;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
	
	.rule-stats {
		display: flex;
		align-items: center;
	}
	
	.stats-item {
		font-size: 24rpx;
		color: #999;
		margin-right: 20rpx;
	}
	
	.rule-actions {
		display: flex;
		padding-top: 16rpx;
		margin-top: 16rpx;
		border-top: 1px solid #f0f0f0;
	}
	
	.action-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 10rpx 20rpx;
		border-radius: 6rpx;
		margin-right: 20rpx;
	}
	
	.edit-btn {
		background-color: #e6f7ff;
		color: #1890ff;
	}
	
	.delete-btn {
		background-color: #fff1f0;
		color: #ff4d4f;
	}
	
	.action-icon {
		font-size: 28rpx;
		margin-right: 8rpx;
	}
	
	.action-text {
		font-size: 26rpx;
	}
	
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40rpx 0;
	}
	
	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 6rpx solid #f3f3f3;
		border-top: 6rpx solid #1BAE76;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.loading-text {
		font-size: 28rpx;
		color: #999;
		margin-top: 20rpx;
	}
	
	.load-more, .load-all {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.load-more {
		color: #1BAE76;
	}
	
	.empty-data {
		padding: 100rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
</style> 